"""区块查询相关路由"""

from flask import Blueprint, request, current_app
from flasgger import swag_from
from utils.response import create_response
from utils.exceptions import BlockchainMiddlewareException

block_bp = Blueprint('block', __name__)

@block_bp.route('/chains/<chain_type>/blocks/latest', methods=['GET'])
@swag_from({
    'tags': ['Block'],
    'summary': '获取最新区块',
    'description': '获取指定区块链的最新区块信息',
    'security': [{'ApiKeyAuth': []}],
    'parameters': [
        {
            'name': 'chain_type',
            'in': 'path',
            'type': 'string',
            'required': True,
            'description': '区块链类型 (fisco_bcos, chainmaker, jdchain, xuperchain)'
        },
        {
            'name': 'with_transactions',
            'in': 'query',
            'type': 'boolean',
            'required': False,
            'default': False,
            'description': '是否包含交易详情'
        }
    ],
    'responses': {
        200: {
            'description': '成功返回最新区块信息',
            'schema': {
                'type': 'object',
                'properties': {
                    'success': {'type': 'boolean'},
                    'data': {
                        'type': 'object',
                        'properties': {
                            'number': {'type': 'integer'},
                            'hash': {'type': 'string'},
                            'parent_hash': {'type': 'string'},
                            'timestamp': {'type': 'integer'},
                            'transactions': {'type': 'array', 'items': {'type': 'object'}},
                            'size': {'type': 'integer'}
                        }
                    },
                    'requestId': {'type': 'string'}
                }
            }
        },
        500: {'description': '查询失败'}
    }
})
def get_latest_block(chain_type):
    """获取最新区块"""
    try:
        # 验证区块链类型
        supported_chains = ['fisco_bcos', 'ethereum', 'chainmaker', 'jdchain', 'xuperchain', 'thanos']
        if chain_type not in supported_chains:
            return create_response(
                success=False,
                error_code='INVALID_CHAIN_TYPE',
                error_message=f'Unsupported chain type: {chain_type}',
                status_code=400
            )
        
        with_transactions = request.args.get('with_transactions', 'false').lower() == 'true'
        
        block = current_app.unified_layer.get_latest_block(chain_type, with_transactions)
        return create_response(data=block)
    except BlockchainMiddlewareException as e:
        return create_response(
            success=False,
            error_code=e.error_code,
            error_message=str(e),
            status_code=400
        )
    except Exception as e:
        return create_response(
            success=False,
            error_code='BLOCK_QUERY_ERROR',
            error_message=str(e),
            status_code=500
        )

@block_bp.route('/chains/<chain_type>/blocks/<block_id>', methods=['GET'])
@swag_from({
    'tags': ['Block'],
    'summary': '获取指定区块',
    'description': '通过区块号或区块哈希获取区块信息',
    'security': [{'ApiKeyAuth': []}],
    'parameters': [
        {
            'name': 'chain_type',
            'in': 'path',
            'type': 'string',
            'required': True,
            'description': '区块链类型'
        },
        {
            'name': 'block_id',
            'in': 'path',
            'type': 'string',
            'required': True,
            'description': '区块号或区块哈希'
        },
        {
            'name': 'with_transactions',
            'in': 'query',
            'type': 'boolean',
            'required': False,
            'default': False,
            'description': '是否包含交易详情'
        }
    ],
    'responses': {
        200: {
            'description': '成功返回区块信息',
            'schema': {
                'type': 'object',
                'properties': {
                    'success': {'type': 'boolean'},
                    'data': {
                        'type': 'object',
                        'properties': {
                            'number': {'type': 'integer'},
                            'hash': {'type': 'string'},
                            'parent_hash': {'type': 'string'},
                            'timestamp': {'type': 'integer'},
                            'transactions': {'type': 'array', 'items': {'type': 'object'}},
                            'size': {'type': 'integer'}
                        }
                    },
                    'requestId': {'type': 'string'}
                }
            }
        },
        404: {'description': '区块不存在'},
        500: {'description': '查询失败'}
    }
})
def get_block_by_id(chain_type, block_id):
    """获取指定区块"""
    try:
        with_transactions = request.args.get('with_transactions', 'false').lower() == 'true'
        
        # 判断是区块号还是区块哈希
        try:
            if block_id.startswith('0x') or len(block_id) >= 40:
                # 区块哈希
                block = current_app.unified_layer.get_block_by_hash(chain_type, block_id, with_transactions)
            else:
                # 区块号
                block = current_app.unified_layer.get_block_by_number(chain_type, int(block_id), with_transactions)
        except ValueError:
            # 如果无法转换为整数，则视为哈希
            block = current_app.unified_layer.get_block_by_hash(chain_type, block_id, with_transactions)
            
        if not block:
            return create_response(
                success=False,
                error_code='BLOCK_NOT_FOUND',
                error_message=f'Block {block_id} not found',
                status_code=404
            )
            
        return create_response(data=block)
    except BlockchainMiddlewareException as e:
        return create_response(
            success=False,
            error_code=e.error_code,
            error_message=str(e),
            status_code=400
        )
    except Exception as e:
        return create_response(
            success=False,
            error_code='BLOCK_QUERY_ERROR',
            error_message=str(e),
            status_code=500
        )